from flask import Blueprint, request, jsonify, g
from extensions import db
from models import Employee, Department, User, Attendance, Performance
from utils import success, error, bad_request, forbidden
from datetime import datetime, date
from sqlalchemy import func, extract
from flask_jwt_extended import jwt_required, get_jwt_identity

# 创建统计API蓝图
statistics_api = Blueprint('statistics_api', __name__, url_prefix='/api/statistics')

# 获取管理员首页统计数据
@statistics_api.route('/dashboard', methods=['GET'])
@jwt_required()
def get_dashboard_data():
    """获取管理员首页统计数据"""
    try:
        # 检查用户权限
        current_user_id = int(get_jwt_identity())
        user = User.query.get(current_user_id)
        
        if not user or user.role != 'admin':
            return forbidden('权限不足').to_response()
        
        # 获取统计数据
        employee_count = Employee.query.count()
        department_count = Department.query.count()
        
        # 计算平均出勤率（本月）
        current_month = datetime.now().month
        current_year = datetime.now().year
        
        total_attendance = Attendance.query.filter(
            extract('month', Attendance.date) == current_month,
            extract('year', Attendance.date) == current_year
        ).count()
        
        total_work_days = 22  # 假设每月22个工作日
        attendance_rate = round((total_attendance / (total_work_days * employee_count)) * 100, 1) if employee_count > 0 else 0
        
        # 计算平均绩效
        avg_performance = db.session.query(func.avg(Performance.score)).scalar() or 0
        performance_avg = round(float(avg_performance), 1)
        
        # 部门分布数据
        department_distribution = db.session.query(
            Department.name,
            func.count(Employee.id).label('count')
        ).join(Employee, Department.id == Employee.department_id).group_by(Department.id, Department.name).all()
        
        department_data = [{"name": dept.name, "value": dept.count} for dept in department_distribution]
        
        # 月度出勤趋势（最近6个月）
        monthly_attendance_data = []
        months = []
        rates = []
        
        for i in range(6):
            month = current_month - i if current_month - i > 0 else current_month - i + 12
            year = current_year if current_month - i > 0 else current_year - 1
            
            month_attendance = Attendance.query.filter(
                extract('month', Attendance.date) == month,
                extract('year', Attendance.date) == year
            ).count()
            
            month_rate = round((month_attendance / (22 * employee_count)) * 100, 1) if employee_count > 0 else 0
            
            months.insert(0, f"{month}月")
            rates.insert(0, month_rate)
        
        monthly_attendance = {
            "months": months,
            "rates": rates
        }
        
        data = {
            "employee_count": employee_count,
            "department_count": department_count,
            "attendance_rate": attendance_rate,
            "performance_avg": performance_avg,
            "department_distribution": department_data,
            "monthly_attendance": monthly_attendance
        }
        
        return success(data=data).to_response()
        
    except Exception as e:
        return error(msg=f'获取统计数据失败: {str(e)}').to_response()

# 获取员工个人数据概览
@statistics_api.route('/personal-overview', methods=['GET'])
@jwt_required()
def get_personal_overview():
    """获取当前员工的个人数据概览"""
    try:
        # 获取当前用户
        current_user_id = int(get_jwt_identity())
        user = User.query.get(current_user_id)
        
        if not user:
            return error(code=401, msg='用户不存在').to_response()
        
        # 获取员工信息
        employee = Employee.query.filter_by(user_id=current_user_id).first()
        if not employee:
            return error(code=404, msg='员工信息不存在').to_response()
        
        # 获取部门信息
        department = Department.query.get(employee.department_id)
        
        # 本月考勤统计
        current_month = datetime.now().month
        current_year = datetime.now().year
        
        attendance_records = Attendance.query.filter(
            Attendance.employee_id == employee.id,
            extract('month', Attendance.date) == current_month,
            extract('year', Attendance.date) == current_year
        ).all()
        
        attendance_days = len([r for r in attendance_records if r.status == 'present'])
        late_count = len([r for r in attendance_records if r.status == 'late'])
        early_count = len([r for r in attendance_records if r.status == 'early'])
        absent_count = len([r for r in attendance_records if r.status == 'absent'])
        
        status_distribution = [
            {"name": "正常出勤", "value": attendance_days},
            {"name": "迟到", "value": late_count},
            {"name": "早退", "value": early_count},
            {"name": "缺勤", "value": absent_count}
        ]
        
        attendance_summary = {
            "attendance_days": attendance_days,
            "late_count": late_count,
            "status_distribution": status_distribution
        }
        
        # 绩效统计
        performances = Performance.query.filter_by(employee_id=employee.id).order_by(Performance.period.desc()).all()
        
        last_performance = performances[0].score if len(performances) > 0 else 0
        
        # 年度绩效趋势（最近4个季度，从旧到新排序）
        yearly_trend = {
            "months": [],
            "scores": []
        }
        
        # 获取最近4条记录并反转顺序（从旧到新）
        recent_performances = performances[:4] if len(performances) >= 4 else performances
        for perf in reversed(recent_performances):
            yearly_trend["months"].append(perf.period)
            yearly_trend["scores"].append(perf.score)
        
        performance_summary = {
            "last_performance": last_performance,
            "yearly_trend": yearly_trend
        }
        
        # 个人信息
        hire_date = employee.created_at.date() if employee.created_at else date.today()
        work_years = (date.today() - hire_date).days // 365
        
        personal_info = {
            "name": employee.name or "未设置",
            "department": department.name if department else "未设置",
            "position": employee.position or "未设置",
            "hire_date": hire_date.strftime('%Y-%m-%d'),
            "work_years": work_years
        }
        
        data = {
            "attendance_summary": attendance_summary,
            "performance_summary": performance_summary,
            "personal_info": personal_info
        }
        
        return success(data=data).to_response()
        
    except Exception as e:
        return error(msg=f'获取个人数据概览失败: {str(e)}').to_response()
